/*
 * Projet industriel VAMP 2012 
 */
package com.vampmobile.android.activity;

import org.json.JSONException;
import org.json.JSONObject;

import com.vampmobile.R;
import com.vampmobile.android.VampApplication;
import com.vampmobile.android.VampCommon.Commons.KINDS;
import com.vampmobile.android.db.VampDatabase;
import com.vampmobile.android.db.VampREST;
import com.vampmobile.android.tools.ActivityParameters;
import com.vampmobile.android.tools.ApplicationMenu;
import com.vampmobile.android.tools.GpsLocationTools;
import com.vampmobile.android.tools.ImageLoader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.Address;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * class vehicle detail FO && AM
 */
public class VehicleDetail extends Activity {
	Double latitude;
	Double longitude;
	Long vehicleId;
	private ImageView mHomeTitle;
	private ImageView mHomeButton;
	private ImageView mBackButton;
	private ImageView mSearchButton;
	private ImageView mQuitButton;
	private ImageView mAccountButton;
	public ProgressDialog mDialog;

	public final static String TAG = "Vehicle detail";

	/*
	 * method used by clicking on button
	 */
	class ClickListener implements android.view.View.OnClickListener {

		private KINDS kind = null;

		public ClickListener(KINDS kind) {
			super();
			this.kind = kind;
		}

		public void onClick(View arg0) {
			switch (kind) {
			case TOOLBAR:
				FrameLayout toolbar = (FrameLayout) findViewById(R.id.toolbar);
				if (toolbar.getVisibility() != View.VISIBLE)
					toolbar.setVisibility(View.VISIBLE);
				else
					toolbar.setVisibility(View.GONE);
				break;
			case QUIT:
				android.os.Process.killProcess(android.os.Process.myPid());
				java.lang.System.exit(0);
				finish();
				break;
			case SEARCH:
				break;
			case BACK:
				Intent i = new Intent();
				i.setClass(getApplicationContext(), Vehicle.class);
				i.setAction(Intent.ACTION_VIEW);
				finish();
				startActivity(i);
				break;
			case PROFILE_TITLE:
				Intent myIntent = new Intent();
				myIntent.setClass(getApplicationContext(), Profile.class);
				myIntent.setAction(Intent.ACTION_VIEW);
				finish();
				startActivity(myIntent);
				break;
			case HOME_TITLE:
				Intent j = new Intent();
				j.setClass(getApplicationContext(), Home.class);
				j.setAction(Intent.ACTION_VIEW);
				finish();
				startActivity(j);
				break;
			case MAP_NAVIGATION:
				goToAdress();
				break;
			case REQUEST:
				showRequestDialog();
				break;
			}
		}

	}
	void goToAdress() {
		Intent i = new Intent(Intent.ACTION_VIEW,
				Uri.parse("google.navigation:q=" + latitude + "," + longitude));
		startActivity(i);
	}
	void request() {
		RequestTask t = new RequestTask();
		t.execute("");
	}

	@Override
	public void onCreate(Bundle icicle) {
		Log.i(TAG, "est OK");
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.vehicle_popup);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView) findViewById(R.id.activityTitle)).setText(ActivityParameters.vehicletDesc);
		vehicleId=ActivityParameters.vehicletId;
		// button of title bar
		mHomeTitle = (ImageView) findViewById(R.id.home_title);
		mHomeTitle.setOnClickListener(new ClickListener(KINDS.TOOLBAR));
		// button of toolbar
		mHomeButton = (ImageView) findViewById(R.id.home);
		mHomeButton.setOnClickListener(new ClickListener(KINDS.HOME_TITLE));
		mBackButton = (ImageView) findViewById(R.id.back_button);
		mBackButton.setOnClickListener(new ClickListener(KINDS.BACK));
		mSearchButton = (ImageView) findViewById(R.id.search);
		mSearchButton.setOnClickListener(new ClickListener(KINDS.SEARCH));
		mQuitButton = (ImageView) findViewById(R.id.quit);
		mQuitButton.setOnClickListener(new ClickListener(KINDS.QUIT));
		mAccountButton = (ImageView) findViewById(R.id.account);
		mAccountButton.setOnClickListener(new ClickListener(
				KINDS.PROFILE_TITLE));
		mDialog = new ProgressDialog(VehicleDetail.this);
		Cursor c =VampDatabase.getInstance(getApplicationContext()).getDbHelper().getVehicles(vehicleId, -1);
		if (c != null && c.moveToFirst()) {
			ImageButton navigate = (ImageButton) findViewById(R.id.popup_btn_navigate);
			navigate.setOnClickListener(new ClickListener(KINDS.MAP_NAVIGATION));
			ImageButton request = (ImageButton) findViewById(R.id.popup_btn_request);
			request.setOnClickListener(new ClickListener(KINDS.REQUEST));
			TextView txt = (TextView) findViewById(R.id.popup_constructor);
			txt.setText(c.getString(c
					.getColumnIndex(VampDatabase.VEHICLE_CONSTRUCTOR_COL)));
			txt = (TextView) findViewById(R.id.popup_model);
			txt.setText(c.getString(c
					.getColumnIndex(VampDatabase.VEHICLE_MODEL_COL)));
			txt = (TextView) findViewById(R.id.popup_year);
			txt.setText(c.getString(c
					.getColumnIndex(VampDatabase.VEHICLE_YEAR_COL)).substring(0, 4));
			txt = (TextView) findViewById(R.id.popup_description);
			txt.setText(c.getString(c
					.getColumnIndex(VampDatabase.VEHICLE_DESCRIPTION_COL)));
			txt = (TextView) findViewById(R.id.popup_distance);
			double dist = c.getDouble(c
					.getColumnIndex(VampDatabase.VEHICLE_DISTANCE_COL));
			if (ActivityParameters.vehicletDistanceUnit=="Km")
				dist = dist/1000;
			txt.setText(dist + " " + ActivityParameters.vehicletDistanceUnit);
			txt = (TextView) findViewById(R.id.popup_status);
			txt.setText(c.getString(c
					.getColumnIndex(VampDatabase.VEHICLE_STATUS_COL)));
			if (c.getInt(c
					.getColumnIndex(VampDatabase.VEHICLE_ISAVAILABLE_COL)) != 1) {
				txt.setTextColor(Color.RED);
				request.setEnabled(false);
			} else {
				request.setEnabled(true);
			}
			latitude = c.getDouble(c.getColumnIndex(VampDatabase.VEHICLE_LATITUDE_COL));
			longitude = c.getDouble(c.getColumnIndex(VampDatabase.VEHICLE_LONGITUDE_COL));	
			Address address = GpsLocationTools.getGpsLocationFromCoordinates(latitude, longitude);
			txt = (TextView) findViewById(R.id.popup_address);
			if (address!=null) {
				txt.setText(address.getAddressLine(0));
				txt = (TextView) findViewById(R.id.popup_zipcode_town);
				txt.setText(address.getPostalCode()+" "+address.getLocality());
			}
			final ImageView thumbnail = (ImageView) findViewById(R.id.popup_vehicle_img);
			String thumbnailUrl = c.getString(c
					.getColumnIndex(VampDatabase.VEHICLE_IMGURI_COL));
			Bitmap bitmap = null;
			if (!TextUtils.isEmpty(thumbnailUrl)) {
				thumbnail.setTag(thumbnailUrl);
				bitmap = VampApplication.getInstance().getImageLoader()
						.loadImage(thumbnailUrl, new ImageLoader.ImageCallback() {
							public void onSuccess(String imageUrl, Bitmap image) {
								if (thumbnail.getTag() == imageUrl) {
									thumbnail.setTag(null);
									thumbnail.setImageBitmap(image);
								}
							}
							public void onFailure(String imageUrl) {
								thumbnail.setTag(null);
							}
						});
			} else {
			}

			if (bitmap == null) {
				thumbnail.setImageDrawable(getApplicationContext().getResources().getDrawable(
						R.drawable.icon));
			} else {
				thumbnail.setImageBitmap(bitmap);
			}
		} else {
			Toast.makeText(getApplicationContext(),
					"Vehicle detail not found!", Toast.LENGTH_LONG)
					.show();
			goVehicle();
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		ApplicationMenu.onCreateOptionsMenu(this, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		ApplicationMenu.onPrepareOptionsMenu(this, menu);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		ApplicationMenu.onOptionsItemSelected(this, item);
		return true;
	}
	public void goVehicle() {
		Intent i = new Intent();
		i.setClass(getApplicationContext(), Vehicle.class);
		finish();
		startActivity(i);
	}
	void showRequestDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle("Request vehicle");
		alert.setMessage("Confirm vehicle request..."
				+"\n"+"Please input your password:" );
		final EditText input = new EditText(this);
		alert.setView(input);
		alert.setPositiveButton("Request", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				SharedPreferences settings = getSharedPreferences(
						VampApplication.PREFS, Context.MODE_PRIVATE);
				if (!input.getText().toString().equals(settings.getString("login_password", "")))
					Toast.makeText(getApplicationContext(),
							"Invalid password!..", Toast.LENGTH_LONG)
							.show();
				else
					request();

			}
		});

		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// Canceled.
					}
				});

		alert.show();
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			goVehicle();
			return true;
		}
		return false;
	}
	private class RequestTask extends AsyncTask<String, Void, Boolean> {

		RequestTask() {
//			mDialog.setMessage("Please wait while sending request...");
//			mDialog.setIndeterminate(true);
//			mDialog.setCancelable(false);
		}

		@Override
		public void onPreExecute() {
//			mDialog.show();
		}

		@Override
		protected Boolean doInBackground(String... args) {
			VampREST.requestVehicle(ActivityParameters.vehicletId);
			JSONObject o = VampREST.getLastRequestVehicle(ActivityParameters.vehicletId);
			if (o==null)
				return false;
			Long id = null;
			try {
				o=o.optJSONObject(VampDatabase.USERREQUEST_TABLE);
				id = o.getLong(VampDatabase.USERREQUEST_ID_COL);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return false;
			}
			if (id==null)
				return false;
			ActivityParameters.currentActivity=ActivityParameters.ACTIVITY_VEHICLE_DETAIL_NFC;
			ActivityParameters.userRequestIdNFC = id;
			Intent i = new Intent(getApplicationContext(), VampNFCControl.class);
			i.setAction(Intent.ACTION_VIEW);
			startActivity(i);
			return true;
		}
		
		

		@Override
		public void onCancelled() {
			onPostExecute(false);
		}

		@Override
		public void onPostExecute(Boolean result) {
//			mDialog.dismiss();
		}
	}

}
